package com.rj.core.validation;


import com.rj.core.constant.DigitsEnum;
import com.rj.core.exception.BaseException;
import com.rj.core.validation.constraints.DigitsField;
import com.rj.util.AssertBeanUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author YFX_RANLUBO
 */
public class DigitsFieldValidator implements ConstraintValidator<DigitsField, Object> {
    /**
     * 是否允许为空
     */
    private boolean allowEmpty;
    /**
     * 属性名称
     */
    private String name;
    /**
     * 最大值
     */
    private int maxInteger;
    private int maxFraction;


    /**
     * 数值类型
     */
    private DigitsEnum digitsEnum;

    @Override
    public void initialize(DigitsField checkField) {
        this.maxInteger = checkField.maxInteger();
        this.maxFraction = checkField.maxFraction();
        this.allowEmpty = checkField.empty();
        this.name = checkField.value();
        this.digitsEnum = checkField.digitsEnum();

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            AssertBeanUtils.check(value, name, allowEmpty)
                    .maxDigits(maxInteger, maxFraction,digitsEnum);
        } catch (BaseException e) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(e.getMessage())
                    .addConstraintViolation();
            return false;
        }

        return true;
    }
}